package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

public class Test {
	public static void main(String[] args) {
		DBCollection coll;
		try {
			
			coll = Data.data("urlCraw");
			DBCursor lobj = coll.find();
			setUp();
			ArrayList<String> lastPing = new ArrayList<String>();
			ArrayList<String> arrUser = new ArrayList<String>();
			while(lobj.hasNext()){
				DBObject dbObject = lobj.next(); 
				lastPing.add(dbObject.get("sitemap").toString());
				arrUser.add(dbObject.get("username").toString());
			}
			
			for (int i = 0; i < lastPing.size(); i++) {
				System.out.println(lastPing.get(i));
				createProducerAndSendAMessage(lastPing.get(i)+"|"+arrUser.get(i));
				try {
					Thread.currentThread().sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
//			connection.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static ActiveMQConnectionFactory connectionFactory;
    private static Connection connection=null;
    private static Session session;
    private static Destination destination;
    private static boolean transacted = false;
	private static void setUp() throws JMSException, IOException {

         connectionFactory = new ActiveMQConnectionFactory(
                 ActiveMQConnection.DEFAULT_USER,
                 ActiveMQConnection.DEFAULT_PASSWORD,
                 "failover:tcp://67.205.109.33:61616");
         
    	 connection = connectionFactory.createConnection();
    	 connection.start();

         session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
         
         destination = session.createQueue("getlinkcraw_a");
     }
 
     private static void createProducerAndSendAMessage(String str) throws JMSException {
   	  
         MessageProducer producer = session.createProducer(destination);
         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
         TextMessage message = session.createTextMessage(str);
         System.out.println("Sending message: " + message.getText());
         producer.send(message);
//         connection.close();
     }
}
